package rpcserver

import (
	corev1 "gluenet/internal/agent/api/core/v1"
	rpcv1 "gluenet/internal/agent/api/rpc/v1"
	"gluenet/internal/agent/depend"
	"gluenet/internal/agent/driver/rpcserver"
	"gluenet/internal/agent/service/proxysvc"
)

const (
	proxy = rpcv1.RPC_SERVICE_PROXY
)

func init() {
	depend.Provide(NewProxyRouter)
	registerRouter(proxy, func(c rpcserver.IRoutes) {
		depend.Invoke(func(d *proxyRouter) {
			d.initRouter(c)
		})
	})
}

type proxyRouter struct {
	proxy *proxysvc.Service
}

func NewProxyRouter(svc *proxysvc.Service) *proxyRouter {
	return &proxyRouter{svc}
}

func (r *proxyRouter) initRouter(c rpcserver.IRoutes) {
	c.Group(`http`).
		Func(`get`, r.proxyGet).
		Func(`post`, r.proxyPost).
		Func(`request`, r.proxyRequest)
}

func (r *proxyRouter) proxyRequest(c *rpcserver.Context) {
	proxyReq := new(corev1.ProxyRequest)
	if err := c.BindJSON(&struct {
		Spec interface{} `json:"spec,omitempty"`
	}{proxyReq}); err != nil {
		return
	}

	resp := r.proxy.ProxyRequest(*proxyReq)
	c.JSON(resp)
}

func (r *proxyRouter) proxyGet(c *rpcserver.Context) {
	proxyReq := new(corev1.ProxyGet)
	if err := c.BindJSON(&struct {
		Spec interface{} `json:"spec,omitempty"`
	}{proxyReq}); err != nil {
		return
	}

	resp := r.proxy.ProxyGet(*proxyReq)
	c.JSON(resp)
}

func (r *proxyRouter) proxyPost(c *rpcserver.Context) {
	proxyReq := new(corev1.ProxyPost)
	if err := c.BindJSON(&struct {
		Spec interface{} `json:"spec,omitempty"`
	}{proxyReq}); err != nil {
		return
	}

	resp := r.proxy.ProxyPost(*proxyReq)
	c.JSON(resp)
}
